package sa.com.sure.ejtimaa.common;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import sa.com.sure.ejtimaa.NotificationActivity;
import sa.com.sure.ejtimaa.R;
import sa.com.sure.ejtimaa.database.Settings;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Environment;
import android.util.Base64;
import android.webkit.MimeTypeMap;
import android.widget.Toast;

public class Helper {
				

	public static String DateFormatWebService  = "yyyy-MM-dd'T'HH:mm:ss";
	
	public static String DateFormatLabel  = "yyyy-MM-dd HH:mm:ss";
	
	public static Date GetDateFormat(String str , String format) throws ParseException
	{
		SimpleDateFormat DateFormat = new SimpleDateFormat(format);
		return DateFormat.parse(str);
	}
	
	public static String GetDateAsStringFormat(Date date , String format) throws ParseException
	{		
	    SimpleDateFormat DateFormat = new SimpleDateFormat(format);
		return DateFormat.format(date);
	}
	
    public static boolean isOnline() {
    	NetworkInfo info = ((ConnectivityManager)AppHelper.getAppContext().getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
        if (info==null || !info.isConnected()) {
                
                Toast.makeText(AppHelper.getAppContext(),"Sorry No Internet Connection",Toast.LENGTH_SHORT).show();
                return false;
        }
        if (info.isRoaming()) {
                return true;
        }
        return true;
        	
    }
    
    public static void StartInternetActivity(String url){  
    	if(isOnline()){    		
		Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
		AppHelper.getAppContext().startActivity(browserIntent);
		}	
    }
    
    public static void StartActivity(Class<?> activity , boolean isRequierdInternet ){
    	
    	if(isRequierdInternet && isOnline())
    	{
    		StartActivity(activity);
    	}	
    }
    
    public static void StartActivity(Class<?> activity ){
    	Class<?> classAcitive =  activity;
    	Intent myIntent  = new Intent(AppHelper.getAppContext(),classAcitive);
    	myIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP |Intent.FLAG_ACTIVITY_NEW_TASK);
    	AppHelper.getAppContext().startActivity(myIntent); 	
    }
    
    public static void StartActivity(Class<?> activity ,Serializable extra  ){
    	Class<?> classAcitive =  activity;
    	Intent myIntent  = new Intent(AppHelper.getAppContext(),classAcitive);
    	myIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP |Intent.FLAG_ACTIVITY_NEW_TASK);
    	myIntent.putExtra("item",extra);
    	AppHelper.getAppContext().startActivity(myIntent); 	
    }
    
    public static void DisplayNotification(String msg)
    {
    	Intent i = new Intent(AppHelper.getAppContext(), NotificationActivity.class);
    	i.putExtra("notificationID", 1);
    	i.putExtra("msg", msg);
    	PendingIntent pendingIntent =PendingIntent.getActivity(AppHelper.getAppContext(), 0, i, PendingIntent.FLAG_CANCEL_CURRENT);
    	AppHelper.getAppContext();
		NotificationManager nm = (NotificationManager)
    	AppHelper.getAppContext().getSystemService(Context.NOTIFICATION_SERVICE);
    	Notification notif = new Notification(
    	R.drawable.ic_launcher,AppHelper.getAppContext().getResources().getString(R.string.notificationdesc), System.currentTimeMillis());
    	CharSequence from = AppHelper.getAppContext().getResources().getString(R.string.notificationtitle);
    	CharSequence message = AppHelper.getAppContext().getResources().getString(R.string.notificationdesc);
    	notif.setLatestEventInfo(AppHelper.getAppContext(), from, message, pendingIntent);
    	notif.vibrate = new long[] { 100, 250, 100, 500};
    	nm.notify(1, notif);
    }
    
    public static Document GetHttpClientResult(String methodName ,String xmlParams) throws Exception{

    	Document doc = null;
    	
    	try 
        {
    		
	    	String serviceUrl = Settings.Instance.GetItem("WebServiceURL").GetValue();	    	
	    	HttpClient httpclient = new DefaultHttpClient();
	        HttpPost httppost = new HttpPost(serviceUrl);	
	        xmlParams = String.format("<%1$s xmlns=\"http://sure.ejtimaa.org/\">%2$s</%1$s>",methodName,xmlParams);
	        StringEntity se = new StringEntity( String.format("<?xml version=\"1.0\" encoding=\"utf-8\"?><soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body>%s</soap:Body></soap:Envelope>", xmlParams), HTTP.UTF_8);
	        se.setContentType("text/xml");
	        httppost.setEntity(se);
	        HttpResponse httpresponse = httpclient.execute(httppost);
	        //InputStream in = httpresponse.getEntity().getContent();
	        HttpEntity httpEntity = httpresponse.getEntity();
	        String str = EntityUtils.toString(httpEntity);
	       
	    	DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
	        try 
	        {
	        	DocumentBuilder db = dbf.newDocumentBuilder();
	    		InputSource is = new InputSource();
	    		is.setCharacterStream(new StringReader(str));
	    	    doc = db.parse(is); 
	    	    
    		} catch (ParserConfigurationException e) {
    		} catch (SAXException e) {
    		} catch (IOException e) {
    		}
	        
	        
	        //in.close();

        } catch (ClientProtocolException e) {
        	DisplayNotification(String.format("%s \n Error Details : %s","Error",e.toString()));
        } catch (IOException e) {
        	DisplayNotification(String.format("%s \n Error Details : %s","Error",e.toString()));
        }
    	
    	if(doc == null)
    	{
    		throw new Exception(AppHelper.getAppContext().getString(R.string.WebServiceURLNotValid)) ;		
    	}
    	
   
    	
		return doc;
    }
    
    public static StringBuilder InputStreamToString(InputStream is) throws IOException 
    {
        String line = "";
        StringBuilder total = new StringBuilder();
        // Wrap a BufferedReader around the InputStream
        
        
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        
        // Read response until the end
        try 
        {
         while ((line = rd.readLine()) != null) 
         { 
           total.append(line); 
         }
        } catch (IOException e) {
         e.printStackTrace();
        }
        
        // Return full string
        
        rd.close();

        return total;
     }
    
    
    
    
    public static boolean CheckURLIsValid(String url){
        try {
          System.setProperty("http.keepAlive", "false");
          HttpURLConnection.setFollowRedirects(false);
          // note : you may also need
          //        HttpURLConnection.setInstanceFollowRedirects(false)
          HttpURLConnection con =
             (HttpURLConnection) new URL(url).openConnection();                    
          int code = con.getResponseCode();
          return ( code == HttpURLConnection.HTTP_OK);
        }
        catch (Exception e) {
           e.printStackTrace();
           return false;
        }
      }
        
    public static void HandleError(Exception ex , boolean showErrorMessage ){
    	DisplayNotification(ex.toString());
    	if(showErrorMessage)
    		Toast.makeText(AppHelper.getAppContext(),ex.toString(), Toast.LENGTH_LONG).show();
    }        
    
    public static void HandleError(Exception ex ){
    	HandleError(ex,false);
    }
    
    public static void HandleError(Exception ex ,int msg ){
    	DisplayNotification(ex.toString());
    	Toast.makeText(AppHelper.getAppContext(),AppHelper.getAppContext().getString(msg), Toast.LENGTH_LONG).show();
    }
    
    public static void ShowToast(int msg){
    	Toast.makeText(AppHelper.getAppContext(),msg, Toast.LENGTH_LONG).show();    	
    }
    
    public static void ShowToast(String msg){
    	Toast.makeText(AppHelper.getAppContext(),msg, Toast.LENGTH_LONG).show();    	
    }
    
    public static void ShowSuccesssMessage(){
    	Toast.makeText(AppHelper.getAppContext(),AppHelper.getAppContext().getString(R.string.OperationSuccessfully), Toast.LENGTH_LONG).show(); 
    }
    
    public static void ShowErrorMessage(){
    	Toast.makeText(AppHelper.getAppContext(),AppHelper.getAppContext().getString(R.string.GlobalError), Toast.LENGTH_LONG).show(); 
    }
    
    public static String ConvertfromByteArrayToBase64(byte[] bytes){
    	return Base64.encodeToString(bytes,Base64.NO_WRAP);
    }
    
    public static byte[]  ConvertfromBase64ToByteArray(String base64) throws IOException{
    	return Base64.decode(base64,Base64.NO_WRAP);
    }
    
    
    public static String GetFilesFolderPath(){
    	
    	return Environment.getExternalStorageDirectory()+"/ejtimaa/files/";
    }
    
    public static String SaveFile(String fileName , byte[] bytes) throws IOException{    
    	
		FileOutputStream stream;
		
    	File directory = new File(GetFilesFolderPath());
    	directory.mkdirs();
		
		stream = new FileOutputStream(GetFilesFolderPath() + fileName);
		stream.write(bytes);
		stream.close();
		stream.flush();
		
		return GetFilesFolderPath() + fileName;
    }
    
    
    public static String SaveFile(String Path , String fileName , byte[] bytes) throws IOException{    
    	
		FileOutputStream stream;
		
    	File directory = new File(GetFilesFolderPath()+ Path);
    	directory.mkdirs();
		
		stream = new FileOutputStream(GetFilesFolderPath()+ Path + fileName);
		stream.write(bytes);
		stream.close();
		stream.flush();
		
		return Path + fileName;
    }
    
    
    public static boolean OpenFile(String fileName){
    	
    	  MimeTypeMap myMime = MimeTypeMap.getSingleton();
    	  File f = new File(GetFilesFolderPath()+fileName);
          Intent newIntent = new Intent(android.content.Intent.ACTION_VIEW);

          //Intent newIntent = new Intent(Intent.ACTION_VIEW);
          String mimeType = myMime.getMimeTypeFromExtension(fileExt(f.getName().toString()).substring(1));
          newIntent.setDataAndType(Uri.fromFile(f),mimeType);
          newIntent.setFlags(newIntent.FLAG_ACTIVITY_NEW_TASK);
          try {
              AppHelper.getAppContext().startActivity(newIntent);
          } catch (android.content.ActivityNotFoundException e) {
              Toast.makeText(AppHelper.getAppContext(), "No handler for this type of file.", 4000).show();
          }
          
          return true;
    }
    
    private static String fileExt(String url) {
        String ext = url.substring(url.lastIndexOf(".") );
        if (ext.indexOf("?")>-1) {
            ext = ext.substring(0,ext.indexOf("?"));
        }
        if (ext.indexOf("%")>-1) {
            ext = ext.substring(0,ext.indexOf("%"));
        }
        return ext;
    }
}
